<?php
/**
******全局变量
**/
class GoodsglobalAction extends Action
{
	public function preMethod()
	{
		R("Mayijie/check_admin");
		$perm_key = session('admin_perm');
		$perm_arr = explode(",",$perm_key);
		if(!in_array(4,$perm_arr)){
			$this->error("无权操作");
		}
	}

	public function index(){
		$Global=M('Goods_global');
		$this->variable=$Global->order('id DESC')->select();
		$this->display();
	}

	public function add(){
		$this->display();
	}
	//插入新全局变量
	public function add_global(){
		$Global=M('Goods_global');
		$data['global_key']=$this->_post('global_key');
		$data['global_name']=$this->_post('global_name');
		$data['note']=$this->_post('note');
		$data['global_value']=stripslashes($_POST['contents']);
		$data['create_time']=time();
		
		$map['global_key']=$data['global_key'];
		$re=$Global->where($map)->select();
		if($re){
			$this->error("此变量已经被使用！");
		}else{
			$ad=$Global->add($data);
			if($ad){$this->success("添加成功！",'refresh');}else{$this->error("添加不成功！请重试");}
		}
	}
	public function refresh(){
		echo "<script>window.parent.location.reload()</script>";
	}

	public function ck_key(){
		$Global=M('Goods_global');
		$map['global_key']=$this->_post('global_key');
		$re=$Global->where($map)->select();
		if($re){
			echo "此变量已经被使用！";
		}
	}

	//更新全局变量
	public function edit(){
		$Global=M('Goods_global');
		$gid=$this->_get('gid');
		$this->variable=$Global->where('id='.$gid)->find();
		$this->display();
	}

	//保存更改
	public function save(){
		$Global=M('Goods_global');
		$map['id']=$this->_post('global_id');
		$data['global_name']=$this->_post('global_name');
		$data['note']=$this->_post('note');
		$data['global_value']=stripslashes($_POST['contents']);
		$re=$Global->where($map)->save($data);
		if($re){
			$this->success("更改成功！",'refresh');
		}else{
			$this->error("更改失败！请重试");
		}
	}	

	//删除全局变量
	public function remove(){
		$Global=M('Goods_global');
		$map['id']=$this->_get('gid');
		//删除内容中上传的图片
		$glb=$Global->where($map)->find();
		preg_match_all("/<img.*?src=\".*?\/uploads\/img\/(.*?)\/(.*?)\" \/>/",$glb['global_value'],$con_pic);
        if(empty($con_pic[2])){
			$re=$Global->where($map)->delete();
		     if($re){echo '1';}else{echo '0';}
		}else{
			for($i=0;$i<count($con_pic[2]);$i++){
				$file="./uploads/img/".$con_pic[1][$i]."/".$con_pic[2][$i];
				if(unlink($file)){
					$re=$Global->where($map)->delete();
					if($re){echo '1';}else{echo '0';}
				}else{
					echo '0';
				}
			}
		}
		
	}

}
?>
